<template>
  <!--<div class="home">-->
  <!--  <img alt="Vue logo" src="../assets/logo.png">-->
  <!--  <HelloWorld msg="Welcome to Your Vue.js App"/>-->
  <!--</div>-->
  <div>

    <!--    增加按钮和搜索框-->

    <div style="margin: 10px 5px">
      <!--      老韩解读
        1. @click="add" 表单点击 新增，就会触发 add方法
      -->
      <el-button type="primary" @click="add">新增</el-button>
      <el-button>其它</el-button>
    </div>

    <div style="margin: 10px 5px">
      <el-input v-model="search" style="width: 30%;" placeholder="请输入关键字"/>
      <el-button style="margin-left: 10px" type="primary" @click="list">检索</el-button>
    </div>


    <!--不加primary没有填充颜色-->
    <!--<el-button type="primary">我的按钮</el-button>-->
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column
          prop="id"
          label="ID"
          sortable
      >
      </el-table-column>
      <el-table-column
          prop="name"
          label="家居名"
      >
      </el-table-column>
      <el-table-column
          prop="maker"
          label="厂家">
      </el-table-column>

      <el-table-column
          prop="price"
          label="价格">
      </el-table-column>

      <el-table-column
          prop="sales"
          label="销量">
      </el-table-column>

      <el-table-column
          prop="stock"
          label="库存">
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="120">
        <!--        老师说明：
              1、这里通过 handleEdit(scope.row)
              2, 可以将当前行数据(scope.row)传递给handleEdit
        -->
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <!--      老韩说明
              1. 如果你点击的确定，就会触发handleDel
              2. 如果你点击的是取消，就不会触发handleDel
          -->
          <el-popconfirm title="确认删除吗?" @confirm="handleDel(scope.row.id)">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加家居的弹窗
     说明:
     1. el-dialog ：v-model="dialogVisible" 表示对话框, 和dialogVisible 变量双向绑定,控制是否显示对话框
     2. el-form :model="form" 表示表单 ,数据和 form数据变量双向绑定
     3. el-input v-model="form.name" 表示表单的input控件，名字为name 需要和后台Javabean[Furn] 属性一致
     4. 在前端中, 对象的属性是可以动态生成的 , 这个知识点，我们在讲前端技术栈讲过
   -->
    <el-dialog title="提示" v-model="dialogVisible" width="30%">
      <!--
        1.:rules="rules" 和rules绑定
        2.ref="form"作用于form表单
        3.prop绑定哪个属性
      -->
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="家居名" prop="name">
          <el-input v-model="form.name" style="width: 50%"></el-input>
          {{ serverValidErrors.name }}
        </el-form-item>
        <el-form-item label="厂商" prop="maker">
          <el-input v-model="form.maker" style="width: 50%"></el-input>
          {{ serverValidErrors.maker }}
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" style="width: 50%"></el-input>
          {{ serverValidErrors.price }}
        </el-form-item>
        <el-form-item label="销量" prop="sales">
          <el-input v-model="form.sales" style="width: 50%"></el-input>
          {{ serverValidErrors.sales }}
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="form.stock" style="width: 50%"></el-input>
          {{ serverValidErrors.stock }}
        </el-form-item>
      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
          </span>
      </template>
    </el-dialog>

    <!--    添加分页导航-->
    <div style="margin: 10px 0">
      <el-pagination
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[2,5,10,15]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

  </div>
</template>

<script>
// // @ is an alias to /src
// import HelloWorld from '@/components/HelloWorld.vue'

import request from "@/uils/request";
import {compile} from "vue";

export default {
  name: 'HomeView',
  components: {},
  data() {
    return {
      //存放后端错误信息
      serverValidErrors: {},
      //增加分页相应的支持
      currentPage: 1,  //当前页
      pageSize: 5, //每页显示记录数
      total: 10, //共有多少记录
      search: '',
      dialogVisible: false,
      form: {},
      tableData: [],
      //定义添加表单的校验规则
      rules: {
        name: [//这里定义多个针对name属性的校验规则
          {required: true, message: "请输入家具名", trigger: "blur"}
        ],
        maker: [
          {required: true, message: "请输入制造厂商名", trigger: "blur"}
        ],
        price: [
          {required: true, message: "请输入价格", trigger: "blur"},
          //使用正则表达式对输入的数据校验
          {pattern: /^[0-9]+(.[0-9]{2})?$/, message: "请输入数字", trigger: "blur"}
        ],
        sales: [{required: true, message: "请输入销量", trigger: "blur"},
          {pattern: /^[1-9]\d*$/, message: "请输入数字", trigger: "blur"}
        ],
        stock: [
          {required: true, message: "请输入库存", trigger: "blur"},
          {pattern: /^[1-9]\d*$/, message: "请输入数字", trigger: "blur"}
        ]
      }
    }
  },
  created() {
    this.list()
  },
  methods: {
    add() {
      //显示对话框
      this.dialogVisible = true
      //清空添加表单数据
      this.form = {}

      //清空上次的校验信息

      //这个是我自己搜的，用下面注释掉的办法有一点小问题
      //即dom是异步更新的的，可能在this.dialogVisible = true之前
      //即对话框的DOM元素不会立即渲染,出现this.$refs.form为undefined的问题，但该问题可以勿略
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields();
        }
      });
      // this.$refs['form'].resetFields()
      //清空上次后端校验信息
      this.serverValidErrors = {}
    },
    save() { //将填写的数据表单，发送给后端   this.form->携带的数据
      //添加、修改

      if (!this.form.id) { //id没有值说明是添加
        //判断验证是否通过
        this.$refs['form'].validate((valid) => {
          if (valid) {  //通过前端校验
            //valid就是表单校验后的结果
            request.post("/api/save", this.form).then(res => {
              //console.log(res)
              if (res.code === 200) {
                this.dialogVisible = false
                this.list()
                this.$message({
                  type: "success",
                  message: "添加成功"
                })
              } else if (res.code === 400) { //后端校验失败
                this.serverValidErrors.name = res.extend.errorMsg.name
                this.serverValidErrors.maker = res.extend.errorMsg.maker
                this.serverValidErrors.price = res.extend.errorMsg.price
                this.serverValidErrors.sales = res.extend.errorMsg.sales
                this.serverValidErrors.stock = res.extend.errorMsg.stock
              }
            })
          } else {
            //提示一个错误的消息框
            this.$message({
              type: "error",
              message: "验证失败"
            })
            return false //放弃提交
          }
        })
      } else {//id有值说明是修改
        request.put("/api/update", this.form).then(res => {
          if (res.code === 200) { //修改成功
            this.$message(
                {
                  type: "success",
                  message: "更新成功"
                }
            )
          } else {
            this.$message(
                {
                  type: "error",
                  message: "更新失败"
                }
            )
          }
          console.log(res)
          this.dialogVisible = false
          this.list()
        })
      }

    },
    list() {
      // request.get("/api/furns").then(res=>{
      //   console.log(res)
      //   // res.data 在main.js做返回处理(拦截器)，将res.data统一返回成res即这里的res就是res.data
      //   this.tableData=res.extend.furnList
      // })
      request.get("/api/furnsByConditionPage", {
        params: { //指定请求携带的参数
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          search: this.search
        }
      }).then(res => {
        this.tableData = res.extend.pageInfo.list
        this.total = res.extend.pageInfo.total
      })
    },
    handleEdit(row) {
      //JSON.stringify(row)将row转成json字符串  (原本是proxy)
      //JSON.parse将json字符串转成json对象
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
      //清空上次的校验信息
      this.$refs['form'].resetFields()
      //清空上次后端校验信息
      this.serverValidErrors = {}
    },
    handleDel(id) {
      request.delete("/api/del/" + id).then(res => {
        if (res.code === 200) { //修改成功
          this.$message(
              {
                type: "success",
                message: "删除成功"
              }
          )
        } else {
          this.$message(
              {
                type: "error",
                message: "删除失败"
              }
          )
        }
        this.list()
      })
    },
    handleCurrentChange(pageNum) { //当用户点击分页请求时会携带pageNum
      this.currentPage = pageNum
      //发出分页请求
      this.list()
    },
    handlePageSizeChange(pageSize) {
      this.pageSize = pageSize
      this.list()
    }
  }
}
</script>
